# config/config_reader.py
from pathlib import Path
from ruamel.yaml import YAML#pip install ruamel.yaml

CONFIG_PATH = Path(__file__).parent / "config.yaml"

# 创建支持 round-trip 的 YAML 对象
yaml = YAML()
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.preserve_quotes = True  # 保留字符串引号
yaml.default_flow_style = False  # 使用块格式（更易读）


def load_config():
    """加载配置文件，保留注释和格式"""
    with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
        return yaml.load(f)


def save_config(config):
    """保存配置，保留原有注释、缩进和顺序"""
    with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
        yaml.dump(config, f)


def get_current_proxy_config():
    """
    返回当前代理配置，格式如：
    qwsdq = {"uid": "62399", "accessName": "qwsdq", "accessPassword": "E8538B779F3D0A7379C1302AD4C0055B"}
    """
    config = load_config()
    proxy_name = config.get("current_proxy")
    if not proxy_name:
        raise ValueError("配置文件中缺少 'current_proxy' 字段")

    proxies = config.get("proxies")
    if not proxies:
        raise ValueError("配置文件中缺少 'proxies' 字段")

    proxy_info = proxies.get(proxy_name)
    if not proxy_info:
        raise ValueError(f"代理 '{proxy_name}' 未定义")

    # 返回副本，避免外部修改影响原始数据
    return proxy_name, dict(proxy_info)


def get_next_unfinished_target():
    """
    获取第一个未完成的目标，并自动注入 prefix 和 suffix
    prefix: url 中 '.html' 之前的部分
    suffix: '.html'
    """
    config = load_config()
    targets = config.get("targets", [])

    for idx, target in enumerate(targets):
        if not target.get("finished", False):
            url = target.get("url", "")
            if not url.endswith(".html"):
                raise ValueError(f"目标 URL 必须以 .html 结尾: {url}")

            # 注入辅助字段（不写回文件）
            target = dict(target)  # 浅拷贝，避免污染原始数据
            target['prefix'] = url.rsplit(".", 1)[0]
            target['suffix'] = ".html"

            return idx, target

    return None, None


def mark_target_as_finished(target_index):
    """标记目标为已完成"""
    config = load_config()
    if config is None:
        raise ValueError("配置文件为空或格式错误")

    if "targets" not in config:
        raise KeyError("配置中缺少 'targets' 字段")

    targets = config["targets"]
    if not isinstance(targets, list):
        raise TypeError("'targets' 字段必须是一个列表")

    if 0 <= target_index < len(targets):
        targets[target_index]["finished"] = True
        save_config(config)  # 保存整个 config
    else:
        raise IndexError("目标索引越界")


def get_start_page_num(target):
    """
    根据配置决定 start_page_num。
    若为 -1，则返回 get_max_current_page_num() + 1
    否则返回配置值。

    :param target: 目标任务字典
    :return: int
    """
    start = target.get("start_page_num", 1)
    if start != -1:
        return start

    # 延迟导入，避免循环依赖
    from myproject.DataManage.DataTable import get_max_current_page_num

    return get_max_current_page_num() + 1

# ======================
# 主程序入口（测试用）
# ======================
if __name__ == "__main__":
    idx, target = get_next_unfinished_target()
    print("下一个未完成目标:")
    print(idx, target)

    proxy_name, proxy_info = get_current_proxy_config()
    print(f"\n当前代理 ({proxy_name}):")
    print(proxy_info)